package com.algorithm.base.greedy;

import org.springframework.stereotype.Service;

/**
 * 135. 分发糖果
 *
 * @author Amadeus
 * @date 2023/11/23
 */
@Service
public class Candy {

    public int candy(int[] ratings) {
        int[] candy = new int[ratings.length];
        candy[0] = 1;
        for (int i = 1; i < ratings.length; i++) {
            candy[i] = 1;
            if (ratings[i] > ratings[i - 1]) {
                candy[i] = candy[i - 1] + 1;
            }
        }

        int sum = candy[ratings.length - 1];
        for (int i = ratings.length - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                candy[i] = Math.max(candy[i + 1] + 1, candy[i]);
            }
            sum += candy[i];
        }

        return sum;
    }

}
